import time

from webargs import fields
from webutils.webargs.bare import parser

from .. import const, params, services


class StateMixin:
    async def on_act_unit_state(self, origin_args, conn):
        await self.broadcaster_app.send_task(
            'broadcast_unit_state',
            origin_args,
            group=const.UserGroup.ALL,
        )
        if str(origin_args['msg']['stat']) == '1':
            self.logger.info('unit start')
        elif str(origin_args['msg']['stat']) == '2':
            self.logger.info('unit end')

    async def on_act_state_message(self, origin_args, conn):
        schema = {
            'type': fields.Str(),
            'mod': fields.Str(required=True),
            'to': params.Receiver(required=True),
            'from': params.Sender(required=False),
            'msg': fields.Dict(required=True),
        }
        args = parser.parse(schema, origin_args)
        room_service = services.RoomService(
            conn,
            room_id=self.session.room_id,
        )
        origin_args['updated_at'] = time.time()
        origin_args['created_at'] = time.time()
        await room_service.update_state(origin_args)

        for group in args['to']['groups']:
            await self.broadcaster_app.send_task(
                'broadcast_state',
                origin_args,
                group=group,
            )
        for user_id in args['to']['users']:
            await self.broadcaster_app.send_task(
                'broadcast_state',
                origin_args,
                user_id=user_id,
            )
